import React, { useState } from 'react'
import { StyleSheet, Text, View, TextInput, ImageBackground } from 'react-native'
import Dialog from '../../../components/dialog'
import { Button } from '@rneui/base';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { LoginAPI, RegisterAPI } from '../../../api/login'
import storage from '../../../utils/storage'

const backgroundImg = require('../../../assets/images/login.jpg')

export default function Login({ navigation }) {
  const [loginFlag, setLoginFlag] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [registerCheck, setRegisterCheck] = useState(false);
  const [loginData, setLoginData] = useState({
    patientName: '',
    tel: '',
    password: '',
    checkPassword: ''
  });
  const [dialogMsg, setDialogMsg] = useState({
    title: '',
    content: ''
  });

  // 注册登录按钮
  const submit = async () => {
    if (loginFlag) {
      // 注册
      const params = {
        patientName: loginData.patientName,
        patientTel: loginData.tel,
        patientPassword: loginData.password
      }
      if (loginData.password != loginData.checkPassword) {
        setDialogMsg({
          title: '注册失败',
          content: '两次输入的密码不一致'
        });
        setLoginData({ ...loginData, checkPassword: '' })
        setRegisterCheck(false);
        setDialogVisible(true);
        return;
      }
      RegisterAPI(params).then(({ data }) => {
        console.log(data, 'data');
        if (data?.code == 0) {
          setDialogMsg({
            title: '注册成功',
            content: '请继续登录'
          });
          setRegisterCheck(true);
          setDialogVisible(true);
          return;
        }
      })
    } else {
      // 登录
      LoginAPI(loginData).then(({ data }) => {
        console.log(data, 'data');
        if (data?.code != 0) {
          setDialogMsg({
            title: '登录失败',
            content: '账号或密码错误'
          });
          setDialogVisible(true);
          return;
        }
        storage.save({
          key: 'userData', 
          data: data.data,
          expires: null,
        });
        navigation.push('UserPage');
      })
    }
  }

  const onDetermine = () => {
    setDialogVisible(!dialogVisible);
    if (loginFlag && registerCheck) {
      setLoginFlag(!loginFlag);
    }
  }

  const onCancel = () => {
    setDialogVisible(!dialogVisible);
  }

  return (
    <View style={styles.container}>
      <ImageBackground
        source={backgroundImg}
        style={styles.imageBackground}
      >
        <View style={styles.loginBox}>
          <Text style={styles.loginBox_title}>某医院门诊诊疗系统</Text>
          <View style={styles.loginBox_input}>
            {
              loginFlag ? <View style={styles.action}>
                <Ionicons name='person-outline' size={20} color='#333' />
                <TextInput
                  style={styles.input}
                  placeholder='请输入姓名'
                  value={loginData.patientName}
                  onChangeText={(val) => setLoginData({ ...loginData, patientName: val })}
                />
              </View> : null
            }
            <View style={styles.action}>
              <Ionicons name='phone-portrait-outline' size={20} color='#333' />
              <TextInput
                style={styles.input}
                placeholder='请输入电话号码'
                value={loginData.tel}
                onChangeText={(val) => setLoginData({ ...loginData, tel: val })}
              />
            </View>
            <View style={styles.action}>
              <Ionicons name='lock-closed-outline' size={20} color='#333' />
              <TextInput
                style={styles.input}
                placeholder='请输入密码'
                secureTextEntry={true}
                value={loginData.password}
                onChangeText={(val) => setLoginData({ ...loginData, password: val })}
              />
            </View>
            {
              loginFlag ? <View style={styles.action}>
                <Ionicons name='lock-closed-outline' size={20} color='#333' />
                <TextInput
                  style={styles.input}
                  placeholder='请再次输入密码'
                  value={loginData.checkPassword}
                  secureTextEntry={true}
                  onChangeText={(val) => setLoginData({ ...loginData, checkPassword: val })}
                />
              </View> : null
            }
          </View>
          <View style={styles.loginBox_Text}>
            <Text onPress={() => setLoginFlag(loginFlag ? false : true)}>点我{loginFlag ? "登录" : "注册"}</Text>
          </View>
          <Button onPress={submit} title={loginFlag ? '注册' : '登录'} />
        </View>
        <Dialog
          onDetermine={onDetermine}
          onCancel={onCancel}
          dialogIsVisible={dialogVisible}
          dialogTitle={dialogMsg.title}
          dialogContent={dialogMsg.content}
        />
      </ImageBackground>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  imageBackground: {
    flex: 1,
    resizeMode: 'cover', // 图片铺满整个容器
    alignItems: 'center',
    justifyContent: 'center'
  },
  loginBox: {
    width: '90%',
    borderRadius: 10,
    padding: 20,
    backgroundColor: 'rgba(255,255,255,0.9)'
  },
  loginBox_title: {
    fontSize: 23,
    fontWeight: 'bold'
  },
  loginBox_input: {
    marginTop: 15,
  },
  action: {
    flexDirection: 'row',
    alignItems: 'center',
    borderColor: '#ddd',
    borderStyle: 'solid',
    borderWidth: 1,
    borderRadius: 5,
    marginBottom: 15,
    paddingLeft: 5,
  },
  input: {
    width: '100%'
  },
  loginBox_Text: {
    width: '100%',
    alignItems: 'flex-end',
    marginBottom: 20,
  }
})